package com.example.mychat.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mychat.entity.*;
import com.example.mychat.mapper.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Tag(name = "消息控制", description = "发送消息")
@Controller
@RequestMapping("/message")
public class MessageController {
    @Resource
    HttpServletRequest req;

    @Resource
    AuthoritiesMapper authoritiesMapper;

    @Resource
    MessageMapper messageMapper;

    @Resource
    FriendMapper friendMapper;

    @Resource
    ThumbMapper thumbMapper;


    @Operation(description = "发布信息")
    @PostMapping("/publish")
    @ResponseBody
    public String publishMessage(@RequestParam String text, @RequestParam int groupId, @RequestParam int type) {
        String username = String.valueOf(req.getSession().getAttribute("username"));
        if (username.equals("null")) {
            return "用户未登录";
        }
        Date time = new Date();
        int day;
        if (type == 1) {
            day = 3;
        } else {
            day = 180;
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(time);
        calendar.add(Calendar.DAY_OF_YEAR, day);
        Date expirationTime = calendar.getTime();
        Long originId;
        if (groupId == -1) {
            Message message = new Message(username, -1, text, time, expirationTime);
            message.setTime(time);
            message.setExpirationTime(expirationTime);
            messageMapper.insert(message);
            originId = message.getId();
            System.out.println(originId);
            message.setOriginId(originId);
            messageMapper.updateById(message);
        } else {
            Message message = new Message(username, -2, text, time, expirationTime);
            messageMapper.insert(message);
            originId = message.getId();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            Authorities authority = authoritiesMapper.selectOne(queryWrapper);
            int userId = authority.getId();
            queryWrapper.clear();
            queryWrapper.eq("userId", userId);
            queryWrapper.eq("groupId", groupId);
            List<Friend> friendList = friendMapper.selectList(queryWrapper);
            for (Friend friend : friendList) {
                messageMapper.insert(new Message(username, friend.getFriendId(), text, time, expirationTime, originId));
            }
        }
        thumbMapper.insert(new Thumb(originId, 0));
        return "success";
    }

}
